package cn.xuqiudong.rpc.protocol.http;

import cn.xuqiudong.rpc.common.model.XqdRequest;
import cn.xuqiudong.rpc.common.model.XqdResponse;
import cn.xuqiudong.rpc.common.util.CommonUtils;
import cn.xuqiudong.rpc.extension.XqdExtensionFactory;
import cn.xuqiudong.rpc.serializer.XqdSerializer;
import cn.xuqiudong.rpc.spring.provider.XqdServiceHolder;
import org.apache.commons.io.IOUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;

/**
 * 描述: 服务端异步处理http请求 返回结果
 * @author Vic.xu
 * @date 2022-03-04
 */
public class XqdHttpServerHandlerRunnable implements Runnable{

    private static XqdSerializer serializer = XqdExtensionFactory.defaultExtendFactory().getAdaptiveXqdExtension(XqdSerializer.class);


    private ServletRequest req;

    private ServletResponse res;

    public XqdHttpServerHandlerRunnable(ServletRequest req, ServletResponse res) {
        this.req = req;
        this.res = res;
    }

    @Override
    public void run() {

            XqdResponse response;
        try {
            byte[] bytes = CommonUtils.toByteArray(req.getInputStream());
            XqdRequest request = serializer.deserialize(bytes, XqdRequest.class);
            // 处理数据
            Object data = XqdServiceHolder.invokeMethod(request);
            response = XqdResponse.success(data);
        } catch (Exception e) {
            response = XqdResponse.error(e.getMessage());
        }
        try {
            byte[] bytes = serializer.serialize(response);
            IOUtils.write(bytes, res.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
